package com.mrdeer.iot.handler;

import com.mrdeer.iot.constant.DriverContext;
import com.mrdeer.iot.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Author: xie jianchu
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class CommandHandler extends MessageToByteEncoder<ByteBuf> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
        out.writeBytes(msg);
    }

    public static void writeCommand(String sn, String command) {
        if (DriverContext.CHANNEL_INFO_MAP.size() > 0) {
            Channel channel = DriverContext.SN_CHANNEL_INFO_MAP.get(sn).getChannel();
            log.info("command:({}) sn:({})", command, sn);

            ByteBuf byteBuf = Unpooled.buffer();
            try {
                byteBuf.writeBytes(ByteUtils.hex2byte(command));
            } catch (Exception e) {
                log.error("bad command to hex:{}", command, e);
                return;
            }
            channel.writeAndFlush(byteBuf).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    log.info("ok:" + command);
                } else {
                    log.error("send data to client exception occur:{}", future.cause());
                }
            });
        } else {
            log.error(DriverContext.CHANNEL_INFO_MAP.toString());
        }
    }
}
